package com.kawa.kemanage.controller;

import com.kawa.kemanage.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping({"/api/upload", "/app/upload"})
@Tag(name = "文件上传", description = "文件上传相关操作")
public class FileUploadController {

    @Value("${file.upload.path:}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:}")
    private String urlPrefix;

    /**
     * 上传图片
     */
    @Operation(summary = "上传图片", description = "上传图片文件")
    @PostMapping("/image")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只能上传图片文件");
            }

            // 检查文件大小 (限制为5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            String fileName = UUID.randomUUID().toString() + extension;

            // 创建日期目录
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String relativePath = "images/" + dateDir + "/" + fileName;

            // 创建目录
            Path uploadDir = Paths.get(uploadPath, "images", dateDir);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            // 返回文件URL (不需要加urlPrefix，因为文件在public目录下)
            String fileUrl = "/uploads/" + relativePath;

            return Result.success(fileUrl);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @Operation(summary = "删除文件", description = "根据文件路径删除文件")
    @DeleteMapping("/file")
    public Result deleteFile(@RequestParam String filePath) {
        try {
            // 安全检查：确保文件路径在允许的目录内
            if (!filePath.startsWith("/uploads/images/")) {
                return Result.error("无效的文件路径");
            }

            // 如果路径以/uploads/开头，去掉开头的/uploads/
            if (filePath.startsWith("/uploads/")) {
                filePath = filePath.substring("/uploads/".length());
            }

            Path fullPath = Paths.get(uploadPath, filePath);

            // 检查文件是否存在
            if (!Files.exists(fullPath)) {
                return Result.error("文件不存在");
            }

            // 删除文件
            Files.delete(fullPath);

            return Result.success("文件删除成功");

        } catch (IOException e) {
            log.error("文件删除失败", e);
            return Result.error("文件删除失败：" + e.getMessage());
        }
    }
}
